package controller;

import model.Page;
import service.RecommendService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "GoodsRecommendType", value = "/goodsRecommend_list")
public class GoodsRecommendTypeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RecommendService rs = new RecommendService();
        int typeID = Integer.parseInt(request.getParameter("type"));
        int pageNumber = 1;
        Page p = new Page();
        if (typeID == 2) {
            if (request.getParameter("pageNumber") != null) {
                pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            }

            if (pageNumber <= 0) {
                pageNumber = 1;
            }
            try {
                p = rs.selectPageByTypeID(typeID, pageNumber);

                if (p.getTotalCount() == 0) {
                    p.setPageNumber(1);
                    p.setTotalPage(1);
                } else {
                    if (pageNumber >= p.getTotalPage() + 1) {
                        p = rs.selectPageByTypeID(typeID, p.getTotalPage());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (request.getParameter("pageNumber") != null) {
                pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            }

            if (pageNumber <= 0) {
                pageNumber = 1;
            }
            try {
                p = rs.selectPageByTypeID(typeID, pageNumber);

                if (p.getTotalCount() == 0) {
                    p.setPageNumber(1);
                    p.setTotalPage(1);
                } else {
                    if (pageNumber >= p.getTotalPage() + 1) {
                        p = rs.selectPageByTypeID(typeID, p.getTotalPage());
                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        request.getSession().setAttribute("p", p);
        request.getSession().setAttribute("t", typeID);
        request.getRequestDispatcher("goodsrecommend_list.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doGet(request, response);
    }

}
